//
//  ImageTool.m
//  Image
//
//  Created by zxs on 2017/6/1.
//  Copyright © 2017年 zxs. All rights reserved.
//

#import "ImageTool.h"

@implementation ImageTool

# pragma mark - public

// 文字水印
+ (UIImage *)waterWithImage:(UIImage *)image text:(NSString *)text point:(CGPoint)point attributed:(NSDictionary * )attributed {
    //1.开启上下文
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
    //2.绘制图片
    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    //添加水印文字
    [text drawAtPoint:point withAttributes:attributed];
    //3.从上下文中获取新图片
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    //4.关闭图形上下文
    UIGraphicsEndImageContext();
    //返回图片
    return newImage;
}

// 图片水印
+ (UIImage *)waterWithImage:(UIImage *)image mask:(UIImage *)mask rect:(CGRect)rect {
    //1.开启上下文
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
    //2.绘制原图
    [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    //3.绘制水印图片到当前上下文
    [mask drawInRect:rect];
    //4.从上下文中获取新图片
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    //5.关闭图形上下文
    UIGraphicsEndImageContext();
    //返回图片
    return newImage;
}

// 圆形裁剪
+ (UIImage *)clipCircleWithImage:(UIImage *)image {
    //1、开启上下文
    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
    //2、设置裁剪区域
    UIBezierPath * path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
    [path addClip];
    //3、绘制图片
    [image drawAtPoint:CGPointZero];
    //4、获取新图片
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    //5、关闭上下文
    UIGraphicsEndImageContext();
    //6、返回新图片
    return newImage;
}

// 带边框的圆形裁剪
+ (UIImage *)clipCircleWithImage:(UIImage *)image borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor {
    //1、开启上下文
    UIGraphicsBeginImageContext(image.size);
    
    //2、设置边框
    CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
    UIBezierPath * path = [UIBezierPath bezierPathWithOvalInRect:rect];
    [borderColor setFill];
    [path fill];
    
    //3、设置裁剪区域
    UIBezierPath * clipPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(rect.origin.x + borderWidth , rect.origin.x + borderWidth , rect.size.width - borderWidth * 2, rect.size.height - borderWidth *2)];
    [clipPath addClip];
    
    //3、绘制图片
    [image drawAtPoint:CGPointZero];
    
    //4、获取新图片
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    //5、关闭上下文
    UIGraphicsEndImageContext();
    //6、返回新图片
    return newImage;
}

// 拉伸图片到指定尺寸：
+ (UIImage *)compressImage:(UIImage *)image toSize:(CGSize)size {
    UIGraphicsBeginImageContext(size);
    CGRect rect = {{0,0}, size};
    [image drawInRect:rect];
    UIImage *compressedImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return compressedImg;
}

@end
